import 'package:flutter/material.dart';
import 'package:pp_uikit/pp_button.dart';
import 'package:pp_uikit/pp_uikit_constants.dart';
import 'package:pp_uikit/pp_uikit_localizations.dart';
import 'package:pp_uikit/theme/pp_default_theme.dart';

/// 左侧leading的点击回调，
/// textEditingController 是搜索框的控制器，暴漏给使用者去处理 是否情况等操作
/// updateTextEdit 是暴漏给使用者的更新方法，该方法在组件的实现setState。
/// 比如想要刷新搜索框 就可以直接调用updateTextEdit()
typedef PPSearchBarLeadClickCallback = Function(
    TextEditingController textEditingController, VoidCallback updateTextEdit);

/// 输入框输入变化的监听
typedef PPSearchBarInputChangeCallback = Function(String input);

/// 输入框提交的监听
typedef PPSearchBarInputSubmitCallback = Function(String input);

/// 按钮点击
typedef PPSearchBarButtonClickCallback = Function(String input);

/// 输入框被点击，只有enable = false时生效
typedef PPSearchBarTextFieldClickCallback = Function();

// ignore: must_be_immutable
class PPSearchBar extends StatefulWidget {
  final FocusNode? focusNode;
  final TextEditingController? textEditingController;
  final PPSearchBarLeadClickCallback? leadClickCallback;

  // final PPSearchBarDismissClickCallback? dismissClickCallback;
  final dynamic leading;
  final PPSearchBarInputChangeCallback? inputChangeCallback;
  final PPSearchBarInputSubmitCallback? inputSubmitCallback;
  final PPSearchBarButtonClickCallback? buttonClickCallback;
  final PPSearchBarTextFieldClickCallback? textFieldClickCallback;
  String? text;
  String? buttonText;
  String? hint;
  final TextStyle? hintStyle;
  final TextStyle? inputTextStyle;
  final TextStyle? dismissStyle;
  final bool showButton;
  final bool showDeleteButton;
  final bool autoFocus;
  final bool enable;
  final bool showSearchIcon;
  final VoidCallback? clearTapCallback;
  final Brightness? brightness;
  final double height;
  Color? searchBackgroundColor;
  Color? buttonTextColor;
  Color? buttonBackgroundColor;
  int? maxLength;
  double? marginRight;

  PPSearchBar(
      {super.key,
      this.focusNode,
      this.leading,
      this.leadClickCallback,
      this.textEditingController,
      this.inputChangeCallback,
      this.inputSubmitCallback,
      this.buttonClickCallback,
      this.textFieldClickCallback,
      this.text,
      this.hint,
      this.buttonText,
      this.hintStyle,
      this.searchBackgroundColor,
      this.buttonTextColor,
      this.buttonBackgroundColor,
      this.height = 30,
      this.inputTextStyle,
      this.enable = true,
      this.showButton = true,
      this.showDeleteButton = true,
      this.showSearchIcon = true,
      this.autoFocus = false,
      this.dismissStyle,
      this.clearTapCallback,
      this.brightness,
      this.marginRight,
      this.maxLength});

  @override
  State<PPSearchBar> createState() => _SearchInputWidgetState();
}

class _SearchInputWidgetState extends State<PPSearchBar> {
  late FocusNode _focusNode;
  late ValueNotifier<bool> valueNotifier;
  late TextEditingController _controller;
  late Color _defaultInputTextColor;
  late Color _defaultHintTextColor;

  @override
  void initState() {
    super.initState();
    _focusNode = widget.focusNode ?? FocusNode();
    TextEditingValue? value = TextEditingValue(text: widget.text ?? "");
    _controller =
        widget.textEditingController ?? TextEditingController.fromValue(value);
    if (widget.textEditingController != null) {
      _controller = widget.textEditingController!;
    } else if (widget.text != null) {
      TextEditingValue? value = TextEditingValue(text: widget.text!);
      _controller = TextEditingController.fromValue(value);
    } else {
      _controller = TextEditingController();
    }
    valueNotifier = ValueNotifier(false);
    _focusNode.addListener(_handleFocusChangeListenerTick);

    _defaultHintTextColor = PPDefaultTheme.instance.colorTextSecondary;
    _defaultInputTextColor = PPDefaultTheme.instance.colorTextBase;
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode.removeListener(_handleFocusChangeListenerTick);
  }

  void _handleFocusChangeListenerTick() {
    if (_focusNode.hasFocus) {
      valueNotifier.value = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    var strings = PPUIKitLocalizations.getLocalizations(context);
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (widget.textFieldClickCallback != null) {
                widget.textFieldClickCallback!();
              }
            },
            child: Container(
              height: widget.height,
              margin: _textFieldMarginRight(),
              decoration: BoxDecoration(
                color: widget.searchBackgroundColor ??
                    PPDefaultTheme.instance.backgroundColor,
                borderRadius: BorderRadius.all(
                  Radius.circular(widget.height / 2),
                ),
              ),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      if (widget.leadClickCallback != null) {
                        widget.leadClickCallback!(_controller, () {
                          setState(() {});
                        });
                      }
                    },
                    child: Visibility(
                      visible: widget.showSearchIcon,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 8),
                        child: Image.asset(
                          "images/icon_search.png",
                          width: widget.height / 2,
                          height: widget.height / 2,
                          package: PPUIKitConstant.packageName,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: TextField(
                        enabled: widget.enable,
                        autofocus: widget.autoFocus,
                        focusNode: _focusNode,
                        maxLength: widget.maxLength,
                        // 控制器属性，控制正在编辑的文本。
                        controller: _controller,
                        // 光标颜色属性，绘制光标时使用的颜色。
                        cursorColor: PPDefaultTheme.instance.brandPrimary,
                        // 光标宽度属性，光标的厚度，默认是2.0。
                        cursorWidth: 2.0,
                        // 样式属性，用于正在编辑的文本的样式。
                        style: widget.inputTextStyle ??
                            TextStyle(
                                textBaseline: TextBaseline.alphabetic,
                                color: _defaultInputTextColor,
                                fontSize: 16),
                        // 装饰（`decoration`）属性，在文本字段周围显示的装饰。
                        decoration: InputDecoration(
                          counterText: '',
                          // 边框属性，装饰的容器周围绘制的形状。
                          border: InputBorder.none,
                          contentPadding: const EdgeInsets.only(right: 6),
                          // 填充颜色属性，填充装饰容器的颜色。
                          fillColor: Colors.transparent,
                          // 是密集属性，输入子项是否是密集形式的一部分（即使用较少的垂直空间）。
                          isDense: true,
                          // 填充属性，如果为`true`，则装饰的容器将填充fillColor颜色。
                          filled: true,
                          // 提示样式属性，用于提示文本（`hintText`）的样式。
                          hintStyle: widget.hintStyle ??
                              TextStyle(
                                fontSize: 14,
                                height: 1,
                                textBaseline: TextBaseline.alphabetic,
                                color: _defaultHintTextColor,
                              ),
                          // 提示文本属性，提示字段接受哪种输入的文本。
                          hintText: widget.hint ?? strings.hintText,
                        ),
                        // 在改变属性，当正在编辑的文本发生更改时调用。
                        onChanged: (content) {
                          valueNotifier.value = true;
                          if (widget.inputChangeCallback != null) {
                            widget.inputChangeCallback!(content);
                          }
                          setState(() {});
                        },
                        onSubmitted: (content) {
                          valueNotifier.value = false;
                          if (widget.inputSubmitCallback != null) {
                            widget.inputSubmitCallback!(content);
                          }
                        }),
                  ),
                  GestureDetector(
                    onTap: () {
                      _controller.clear();
                      if (widget.clearTapCallback != null) {
                        widget.clearTapCallback!();
                      }
                      setState(() {});
                      // 获取焦点
                      FocusScope.of(context).requestFocus(_focusNode);
                    },
                    child: Visibility(
                      visible: widget.showDeleteButton &&
                          _controller.text.isNotEmpty,
                      child: Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: Image.asset(
                          "images/icon_delete.png",
                          width: widget.height / 2,
                          height: widget.height / 2,
                          package: PPUIKitConstant.packageName,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Offstage(
          offstage: !widget.showButton,
          child: PPButton(
            widget.buttonText ?? strings.search,
            onPressed: () {
              if (widget.buttonClickCallback != null) {
                widget.buttonClickCallback!(_controller.text);
              }
            },
            textColor: widget.buttonTextColor ?? Colors.white,
            bgColor: widget.buttonBackgroundColor ??
                PPDefaultTheme.instance.brandPrimary,
            maxHeight: 30,
            maxWidth: 60,
            radius: 15,
          ),
        ),
      ],
    );
  }

  EdgeInsetsGeometry? _textFieldMarginRight() {
    if (widget.showButton) {
      return const EdgeInsets.only(right: 8);
    }
    return widget.marginRight != null
        ? EdgeInsets.only(right: widget.marginRight!)
        : null;
  }
}
